package com.jike.noobmoney.mvp.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.image.imagepicker.ImagePicker;
import com.image.imagepicker.bean.ImageItem;
import com.image.imagepicker.ui.ImageGridActivity;
import com.image.imagepicker.ui.ImagePreviewDelActivity;
import com.jike.noobmoney.R;
import com.jike.noobmoney.adapter.ImagePickerAdapter;
import com.jike.noobmoney.adapter.StepAdapter;
import com.jike.noobmoney.adapter.TaskCategoryAdapter;
import com.jike.noobmoney.adapter.TimeCategoryAdapter;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.BuzhouEntity;
import com.jike.noobmoney.entity.CateListEntity;
import com.jike.noobmoney.entity.MoneyEntity;
import com.jike.noobmoney.entity.MyPushDetailEntity;
import com.jike.noobmoney.entity.ProByCateEntity;
import com.jike.noobmoney.helper.ImageLoader;
import com.jike.noobmoney.mvp.presenter.AppPresenter;
import com.jike.noobmoney.mvp.presenter.TaskPresenter;
import com.jike.noobmoney.mvp.presenter.UserPresenter;
import com.jike.noobmoney.mvp.view.widget.HorizontalListView;
import com.jike.noobmoney.mvp.view.widget.MyGridView;
import com.jike.noobmoney.mvp.view.widget.MyListView;
import com.jike.noobmoney.mvp.view.widget.PushDialog;
import com.jike.noobmoney.mvp.view.widget.TaskTypeDialog;
import com.jike.noobmoney.net.IView;
import com.jike.noobmoney.util.AppUtils;
import com.jike.noobmoney.util.ComUtils;
import com.jike.noobmoney.util.Constant;
import com.jike.noobmoney.util.Logger;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.SignUtil;
import com.jike.noobmoney.util.ToastUtils;

import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by kekex on 2019/3/19.
 * 发布任务
 */

public class PushTaskUpdateActivity extends BaseActivity implements IView, ImagePickerAdapter.OnRecyclerViewItemClickListener,StepAdapter.OnCartClick {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;


    public static final int IMAGE_ITEM_ADD = -1;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_type_title)
    TextView tvTypeTitle;
    @BindView(R.id.rl_task_type)
    RelativeLayout rlTaskType;

    @BindView(R.id.et_danjia)
    EditText etDanjia;
    @BindView(R.id.et_shuliang)
    EditText etShuliang;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.tv_need_chongzhi)
    TextView tvNeedChongzhi;
    @BindView(R.id.et_info)
    EditText etInfo;
    @BindView(R.id.et_taskname)
    EditText etTaskName;
    @BindView(R.id.tv_chongzhi)
    TextView tvChongzhi;
    @BindView(R.id.tv_fabu)
    TextView tvFabu;
    @BindView(R.id.ck_zhiding)
    ImageView ckZhiding;
    @BindView(R.id.tv_ecode)
    TextView tvEcode;
    @BindView(R.id.tv_lianjie)
    TextView tvLianjie;
    @BindView(R.id.iv_pic)
    ImageView ivPic;
    @BindView(R.id.et_lianjie)
    EditText etLianjie;
    @BindView(R.id.ll_view)
    LinearLayout llView;
    @BindView(R.id.iv_jiantou)
    ImageView ivJiantou;
    @BindView(R.id.lv_show)
    MyListView listView;
    @BindView(R.id.tv_percent)
    TextView  tv_percent;

    @BindView(R.id.et_tasktitle)
    EditText et_tasktitle;

    @BindView(R.id.tv_zhiding_price)
    TextView tv_zhiding_price;

    @BindView(R.id.hlv_list)
    HorizontalListView hlv_list;
    @BindView(R.id.hlv_list_xj)
    HorizontalListView hlv_list_xj;
    @BindView(R.id.hlv_list_cf)
    HorizontalListView hlv_list_cf;
    @BindView(R.id.hlv_list_zq)
    HorizontalListView hlv_list_zq;
    @BindView(R.id.cb_check_other)
    CheckBox cb_check_other;
    @BindView(R.id.gd_type)
    MyGridView rv_list;

    private int maxImgCount = 9;               //允许选择图片最大数
    private ArrayList<ImageItem> selImageList = new ArrayList<>(); //当前选择的所有图片
    public static final int REQUEST_CODE_PREVIEW = 101;
    public static final int REQUEST_CODE_SELECT = 100;
    public double topmoney;

    private TaskPresenter taskPresenter;
    private List<CateListEntity.CatelistBean> mData = new ArrayList<>();
    private ImagePickerAdapter adapter;
    private AppPresenter appPresenter;
    private int typePostion = 0;
    private UserPresenter userPresenter;
    private String userid;
    private double money;
    private int c_id = 1;
    private boolean iszhiding = false;
    private double zhidingNum = 0;
    private String step = "";
    private String opentype = "";
    private String openurl = "";
    private String imageurl = "";
    private ImageView image;
    private String type;
    private boolean isGuanfang = false;
    private String taskId;
    ArrayList<MyPushDetailEntity.TaskstepBean> taskstepBeans=new ArrayList<>();
    public StepAdapter stepAdapter;
    private TimeCategoryAdapter taskCategoryAdapter2;
    private TaskCategoryAdapter taskCategoryAdapter;
    private ArrayList<CateListEntity.CatelistBean> list=new ArrayList<CateListEntity.CatelistBean>();
    //只要切换任务类型就默认值
    private boolean flag;
    private TimeCategoryAdapter finishAdapter2, downtimeAdapterXJ, autotimeAdapterZQ,taskCategoryAdapterCF;

    private ArrayList<ProByCateEntity.ProBean> finishtime =new ArrayList<>();
    private ArrayList<ProByCateEntity.ProBean> downtime =new ArrayList<>();
    private ArrayList<ProByCateEntity.ProBean> autotime =new ArrayList<>();
    private String limittime_id1,limittime_id2,limittime_id3,isrepeat;
    //服务费百分比
    private double percent;
    @Override
    protected int layoutResID() {
        return R.layout.activity_push_task_v3;
    }

    /**
     * 如果要全屏,重写这个方法返回false
     */
    public Boolean isfits() {
        return true;
    }

    /**
     * 如果要白色主题,重写这个方法返回false
     */
    public boolean ismain() {
        return true;
    }

    @Override
    protected void initData() {
        tvTitle.setText("发布任务");
        if (getIntent() != null) {
            taskId = getIntent().getStringExtra(UserTaskDetailActivity.t_id);
        }
        userPresenter = new UserPresenter(this);  //获取余额
        taskPresenter = new TaskPresenter(this);  //发布任务
        appPresenter = new AppPresenter(this);    //上传图片


        taskCategoryAdapter=new TaskCategoryAdapter(context,list);
        rv_list.setAdapter(taskCategoryAdapter);
        rv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                flag=true;
                taskCategoryAdapter.setSelectedPosition(i);
                taskCategoryAdapter.notifyDataSetChanged();
                CateListEntity.CatelistBean bean=(CateListEntity.CatelistBean)adapterView.getAdapter().getItem(i);
                c_id=bean.getC_id();
                taskPresenter.getProByCate(c_id+"",ConstantValue.RequestKey.get_pro_by_cate);
            }
        });

        finishAdapter2 =new TimeCategoryAdapter(context,finishtime);
        hlv_list.setAdapter(finishAdapter2);
        hlv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ProByCateEntity.ProBean bean = (ProByCateEntity.ProBean)adapterView.getAdapter().getItem(i);
                finishAdapter2.setSelectedPosition(i);
                finishAdapter2.notifyDataSetChanged();
                limittime_id1=bean.getLimittime_id();
            }
        });
        //下架
        downtimeAdapterXJ =new TimeCategoryAdapter(context,downtime);
        hlv_list_xj.setAdapter(downtimeAdapterXJ);
        hlv_list_xj.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ProByCateEntity.ProBean bean = (ProByCateEntity.ProBean)adapterView.getAdapter().getItem(i);
                downtimeAdapterXJ.setSelectedPosition(i);
                downtimeAdapterXJ.notifyDataSetChanged();
                limittime_id2=bean.getLimittime_id();
            }
        });
        downtimeAdapterXJ.notifyDataSetChanged();
        //重复
        taskCategoryAdapterCF=new TimeCategoryAdapter(context, Constant.list3);
        hlv_list_cf.setAdapter(taskCategoryAdapterCF);
        hlv_list_cf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ProByCateEntity.ProBean bean = (ProByCateEntity.ProBean)adapterView.getAdapter().getItem(i);
                taskCategoryAdapterCF.setSelectedPosition(i);
                taskCategoryAdapterCF.notifyDataSetChanged();
                isrepeat=bean.getLimittime_id();
            }
        });
        taskCategoryAdapterCF.notifyDataSetChanged();

        //审核周期
        autotimeAdapterZQ =new TimeCategoryAdapter(context, autotime);
        hlv_list_zq.setAdapter(autotimeAdapterZQ);
        hlv_list_zq.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ProByCateEntity.ProBean bean = (ProByCateEntity.ProBean)adapterView.getAdapter().getItem(i);
                autotimeAdapterZQ.setSelectedPosition(i);
                autotimeAdapterZQ.notifyDataSetChanged();
                limittime_id3=bean.getLimittime_id();
            }
        });
        autotimeAdapterZQ.notifyDataSetChanged();


        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);

        etDanjia.addTextChangedListener(new TextWatch(1));
        etShuliang.addTextChangedListener(new TextWatch(2));

        //获取余额
        getMoney();

        setZhiding(iszhiding);

        refreshType(true);
        Intent intent = getIntent();
        if (intent != null) {
            type = intent.getStringExtra("type");
        }
        stepAdapter=new StepAdapter(this,taskstepBeans);
        stepAdapter.setOnCartClick(this);
        listView.setAdapter(stepAdapter);
        getData();
        if ("guanfang".equals(type)) {
            isGuanfang = true;
            tvTypeTitle.setText("官方推荐");
            ivJiantou.setVisibility(View.GONE);
        }else
        {
         // getTaskType();
        }

    }

    View xkview;

    private void removeView(View layout) {
        llView.removeView(layout);
    }

    private boolean isPre() {
        for (int i = 0; i < listView.getChildCount(); i++) {
            View view = listView.getChildAt(i);
            EditText etText = (EditText) view.findViewById(R.id.et_text);
            ImageView ivPic = (ImageView) view.findViewById(R.id.iv_pic);
            String trim = etText.getText().toString().trim();
            String tag = "" + ivPic.getTag();
            if (!(!TextUtils.isEmpty(trim) && !TextUtils.isEmpty(tag))) {
                ToastUtils.showShortToastSafe("请填写步骤说明并且上传示例图片");
                return false;
            }
        }
        return true;
    }

    private void refreshType(boolean isSelected) {
        if (isSelected) {
            opentype = "1";
            //选择二维码
            tvEcode.setSelected(true);
            tvLianjie.setSelected(false);
            tvEcode.setTextColor(getResources().getColor(R.color.white));
            tvLianjie.setTextColor(getResources().getColor(R.color.maincolor));

            ivPic.setVisibility(View.VISIBLE);
            etLianjie.setVisibility(View.GONE);
        } else {
            opentype = "2";
            //选择链接
            tvEcode.setSelected(false);
            tvLianjie.setSelected(true);
            tvEcode.setTextColor(getResources().getColor(R.color.maincolor));
            tvLianjie.setTextColor(getResources().getColor(R.color.white));

            ivPic.setVisibility(View.GONE);
            etLianjie.setVisibility(View.VISIBLE);
        }

        ivPic.setOnClickListener(v -> {
            ImagePicker.getInstance().setSelectLimit(1);
            ImagePicker.getInstance().setCrop(false);
            ImagePicker.getInstance().setShowCamera(true);
            ImagePicker.getInstance().setMultiMode(true);
            Intent intent1 = new Intent(context, ImageGridActivity.class);
            startActivityForResult(intent1, 110);
        });


    }

    private double danjia = 0;
    private int shuliang = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /**
     * 获取任务详情
     */
    private void getData() {
        showProgress();
        taskPresenter.getMyPushDetail(taskId, ConstantValue.RequestKey.my_push_detail);
    }



    class TextWatch implements TextWatcher {

        private int WatchNum;


        public TextWatch(int num) {
            WatchNum = num;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (WatchNum == 1) {
                if (charSequence.length() > 0) {
                    try {
                        String danjiaStr = charSequence.toString();
                        danjia = Double.valueOf(danjiaStr);
                    } catch (Exception e) {
                        danjia = 0;
                    }

                } else {
                    danjia = 0;
                }
            }

            if (WatchNum == 2) {
                if (charSequence.length() > 0) {
                    try {
                        String shuliangStr = charSequence.toString();
                        shuliang = Integer.parseInt(shuliangStr);
                    } catch (Exception e) {
                        shuliang = 0;
                    }
                } else {
                    shuliang = 0;
                }
            }
            changTotalAndNeed();
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    }

    /**
     * 修改总价
     */
    private void changTotalAndNeed() {
        if (ckZhiding.isSelected()) {
           // zhidingNum = shuliang * 2;
            zhidingNum = topmoney;
        } else {
            zhidingNum = 0;
        }
        double total = danjia * shuliang*(1+percent) + zhidingNum;
        tvTotal.setText(String.format("%.2f", total));
        if (total < money) {
            tvNeedChongzhi.setText("0");
        } else {
            tvNeedChongzhi.setText(String.format("%s", ComUtils.sub(total, money)));
        }
    }

    /**
     * 获取余额
     */
    private void getMoney() {
        showProgress();
        userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
        userPresenter.moneyView(userid, ConstantValue.RequestKey.getMoneyView);
    }

    private List<BuzhouEntity> students = new ArrayList<>();

    @OnClick({R.id.iv_back, R.id.ll_zhiding, R.id.rl_task_type, R.id.tv_ecode, R.id.tv_lianjie, R.id.tv_chongzhi, R.id.tv_fabu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_task_type:
                //选择类型
                if (!isGuanfang) {
                    showTaskTypeDialog();
                }
                break;
            case R.id.tv_chongzhi:
                //充值
                startActivity(new Intent(context, ChongZhiActivity.class));
                break;
            case R.id.ll_zhiding:
                //是否置顶
                setZhiding(iszhiding);
                break;
            case R.id.tv_ecode:
                refreshType(true);
                break;
            case R.id.tv_lianjie:
                refreshType(false);
                break;
            case R.id.tv_fabu:
                if (isPre()) {
                    if (students.size() > 0) {
                        students.clear();
                    }
                    for (int i = 0; i < listView.getChildCount(); i++) {
                        View view1 = listView.getChildAt(i);
                        EditText etText = (EditText) view1.findViewById(R.id.et_text);
                        ImageView ivPic = (ImageView) view1.findViewById(R.id.iv_pic);
                        CheckBox cbCheck = (CheckBox) view1.findViewById(R.id.cb_check);
                        BuzhouEntity student = new BuzhouEntity();
                        student.setStep_text(etText.getText().toString().trim());
                        student.setStep_pic("" + ivPic.getTag());
                        student.setFlag(cbCheck.isChecked() ? "1" : "0");
                        students.add(student);
                    }
                    String jsonStr = new Gson().toJson(students);
                    Logger.e("xuke", "json = " + jsonStr);
                    step = jsonStr;
                    //发布
                    if (!TextUtils.isEmpty(jsonStr)) {
                        PushDialog instance = PushDialog.getInstance(String.valueOf(c_id));
                        instance.show(getSupportFragmentManager(), "pushdialog");
                        instance.setClickCallback(new PushDialog.OnClickCallback() {
                            @Override
                            public void cancel() {
                                instance.dismiss();
                            }

                            @Override
                            public void confirm() {
                                instance.dismiss();
                                fabu("");
                            }
                        });
                    } else {
                        ToastUtils.showShortToastSafe("请填写操作步骤");
                    }
                }
                break;
        }
    }

    private void setZhiding(boolean iszhiding) {
        ckZhiding.setSelected(this.iszhiding);
        this.iszhiding = !iszhiding;
        changTotalAndNeed();
    }

    /**
     * 准备发布
     */
    private boolean isPer() {
        if (selImageList.size() == 0) {
            ToastUtils.showShortToastSafe("请添加示例图片");
            return false;
        }
        return true;
    }
    public CateListEntity.CatelistBean getBeanByName(ArrayList<CateListEntity.CatelistBean> list, String c_id)
    {
        CateListEntity.CatelistBean selectbean=null;
        for(CateListEntity.CatelistBean bean :list){
            if((""+bean.getC_id()).equals(c_id)){
                selectbean=bean;
            }
        }
        return selectbean;
    }

    public ProByCateEntity.ProBean getProBeanByName(ArrayList<ProByCateEntity.ProBean> list,String id)
    {
        ProByCateEntity.ProBean selectbean=null;
        for(ProByCateEntity.ProBean bean :list)
        {
            if(bean.getLimittime_id().equals(id)){
                selectbean=bean;
            }
        }

        return selectbean;
    }



    /**
     * 发布
     */
    private void fabu(String images) {
        String userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
//        if (mData != null && mData.size() > 0) {
//            CateListEntity.CatelistBean catelistBean = mData.get(typePostion);
//            c_id = catelistBean.getC_id();
//        } else {
//            c_id = 10010;
//        }

        if (isGuanfang) {
            c_id = 2;
        }

        double money = this.danjia;
        int shuliang = this.shuliang;

        String taskname = etTaskName.getText().toString().trim();
        String tasktitle=et_tasktitle.getText().toString().trim();
        String text = etInfo.getText().toString().trim();

        if ("1".equals(opentype)) {
            openurl = imageurl;
        } else {
            openurl = etLianjie.getText().toString().trim();
        }

        if (c_id == 10010){
            ToastUtils.showShortToastSafe("请先选择任务类型");
            return;
        }

        if (TextUtils.isEmpty(openurl)) {
            ToastUtils.showShortToastSafe("请先选择任务打开方式并上传相关二维码或者链接");
            return;
        }

        if (TextUtils.isEmpty(taskname)) {
            ToastUtils.showShortToastSafe("任务名称必填");
            return;
        }
        if (TextUtils.isEmpty(tasktitle)) {
            ToastUtils.showShortToastSafe("发布标题必填");
            return;
        }
        if (money==0.00) {
            ToastUtils.showShortToastSafe("请输入正确的单价");
            return;
        }
        if (shuliang==0) {
            ToastUtils.showShortToastSafe("请输入正确的数量");
            return;
        }
        showProgress();

        TreeMap<String,String> paraMap = new TreeMap<String,String>();
        paraMap.put("t_id",taskId);
        paraMap.put("u_id",userid);
        paraMap.put("c_id",c_id+"");
        paraMap.put("taskname",taskname);
        paraMap.put("title",tasktitle);
        paraMap.put("money",money+"");
        paraMap.put("number",shuliang+"");
        paraMap.put("text",text);
        paraMap.put("top",ckZhiding.isSelected()? "1" : "0");
        paraMap.put("opentype",opentype);
        paraMap.put("openurl",openurl);
        paraMap.put("step",step);
        paraMap.put("isinfo",cb_check_other.isChecked() ? "1" : "0");
        paraMap.put("isrepeat",isrepeat);
        paraMap.put("limittime_id1",limittime_id1);
        paraMap.put("limittime_id2",limittime_id2);
        paraMap.put("limittime_id3",limittime_id3);
        String sign= SignUtil.generateSignature(paraMap,Constant.VALUE);
        Log.e("sign",sign);
        taskPresenter.pushTaskUpdateLast(taskId,userid, c_id, taskname,tasktitle, money, shuliang,text, ckZhiding.isSelected(),
                opentype, openurl, step,cb_check_other.isSelected(),isrepeat,limittime_id1,limittime_id2,limittime_id3,sign, ConstantValue.RequestKey.push_task_update);
    }

    /**
     * 获取发布类型
     */
    private void showTaskTypeDialog() {
        showProgress();
        taskPresenter.getCatelist(ConstantValue.RequestKey.task_type);
    }
    private void getTaskType()
    {
        taskPresenter.getCatelist(ConstantValue.RequestKey.task_type_show);
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                pickImage();
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    private void pickImage() {
        //打开选择,本次允许选择的数量
        ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
        ImagePicker.getInstance().setCrop(false);
        ImagePicker.getInstance().setShowCamera(true);
        ImagePicker.getInstance().setMultiMode(true);
        Intent intent1 = new Intent(context, ImageGridActivity.class);
        startActivityForResult(intent1, REQUEST_CODE_SELECT);
    }
    @Override
    public void delete(MyPushDetailEntity.TaskstepBean bean) {
        if(listView.getChildCount()==1)
        {
            Toast.makeText(context,"至少添加一个步骤说明",Toast.LENGTH_SHORT).show();
            return;
        }
        taskstepBeans.remove(bean);
        stepAdapter.setList(taskstepBeans);
    }

    @Override
    public void add() {
        if(listView.getChildCount()<=10) {
            MyPushDetailEntity.TaskstepBean bean = new MyPushDetailEntity.TaskstepBean();
            taskstepBeans.add(bean);
            stepAdapter.setList(taskstepBeans);
        }
    }

    public HashMap<Integer,MyPushDetailEntity.TaskstepBean> map=new HashMap<Integer, MyPushDetailEntity.TaskstepBean>();
    public int position;
    @Override
    public void addPic(MyPushDetailEntity.TaskstepBean bean, int positon) {
        map.put(positon,bean);
        position=positon;
        ImagePicker.getInstance().setSelectLimit(1);
        ImagePicker.getInstance().setCrop(false);
        ImagePicker.getInstance().setShowCamera(true);
        ImagePicker.getInstance().setMultiMode(true);
        Intent intent1 = new Intent(PushTaskUpdateActivity.this, ImageGridActivity.class);
        PushTaskUpdateActivity.this.startActivityForResult(intent1, 1110);
    }
    @SuppressWarnings("unchecked")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        }

        //二维码添加返回
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 110) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    showProgress();
                    appPresenter.submituploadfile(new File(images.get(0).getPath()), "uploadfile");
                }
            }
        }


        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == 1110) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    Logger.e("xuke", "--->" + images.get(0));
                    showProgress();
                    appPresenter.markuploadfile(new File(images.get(0).getPath()), "step"+position);
                }
            }
        }
    }


    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        dismissProgress();
        if (ConstantValue.RequestKey.getMoneyView.equals(actionType)) {
            //获取用户余额
            MoneyEntity.UserBean userBean = (MoneyEntity.UserBean) data;
            money = userBean.getMoney();
        }

        if (ConstantValue.RequestKey.task_type_show.equals(actionType)) {
            List<CateListEntity.CatelistBean> catelist = (List<CateListEntity.CatelistBean>) data;

            if (catelist != null && catelist.size() > 0) {
                mData.clear();
                mData.addAll(catelist);


                //最新修改
                list.clear();
                list.addAll(catelist);
            }

            CateListEntity.CatelistBean bean=getBeanByName(list,c_id+"");
            if(bean!=null){
                taskCategoryAdapter.setSelectedPosition(list.indexOf(bean));
                taskCategoryAdapter.notifyDataSetChanged();
                c_id=mData.get(list.indexOf(bean)).getC_id();
                //根据分类获取属性
                taskPresenter.getProByCate(c_id+"",ConstantValue.RequestKey.get_pro_by_cate);
            }

        }

        if (ConstantValue.RequestKey.task_type.equals(actionType)) {
            List<CateListEntity.CatelistBean> catelist = (List<CateListEntity.CatelistBean>) data;

            if (catelist != null && catelist.size() > 0) {
                mData.clear();
                mData.addAll(catelist);
            }
            TaskTypeDialog bottomDialog = TaskTypeDialog.getInstance(mData);
            bottomDialog.show(getSupportFragmentManager(), "task_type");
            bottomDialog.setClickCallback(new TaskTypeDialog.OnClickCallback() {
                @Override
                public void onItemClick(int position) {
                    bottomDialog.dismiss();
                    typePostion = position;
                    CateListEntity.CatelistBean catelistBean = mData.get(position);
                    tvTypeTitle.setText(catelistBean.getCatename());
                    c_id=catelistBean.getC_id();
                }

                @Override
                public void cancel() {
                    bottomDialog.dismiss();
                }
            });
        }
        if (ConstantValue.RequestKey.get_pro_by_cate.equals(actionType)) {
            ProByCateEntity entity=(ProByCateEntity)data;
            finishtime.clear();
            finishtime.addAll(((ProByCateEntity) data).getFinishtime());
            if(flag){
                finishAdapter2.setSelectedPosition(0);
                finishAdapter2.notifyDataSetChanged();
                limittime_id1 = finishtime.get(0).getLimittime_id();
            }else {
                ProByCateEntity.ProBean fbean = getProBeanByName(finishtime, limittime_id1);
                if (fbean != null) {
                    int i = finishtime.indexOf(fbean);
                    finishAdapter2.setSelectedPosition(i);
                    finishAdapter2.notifyDataSetChanged();
                    limittime_id1 = finishtime.get(i).getLimittime_id();
                }
            }

            downtime.clear();
            downtime.addAll(((ProByCateEntity) data).getDowntime());
            if(flag){
                downtimeAdapterXJ.setSelectedPosition(0);
                downtimeAdapterXJ.notifyDataSetChanged();
                limittime_id2 = downtime.get(0).getLimittime_id();
            }else {
                ProByCateEntity.ProBean dbean = getProBeanByName(downtime, limittime_id2);
                if (dbean != null) {
                    int i = downtime.indexOf(dbean);
                    downtimeAdapterXJ.setSelectedPosition(i);
                    downtimeAdapterXJ.notifyDataSetChanged();
                    limittime_id2 = downtime.get(i).getLimittime_id();
                }
            }
            autotime.clear();
            autotime.addAll(((ProByCateEntity) data).getAutotime());
            if(flag){
                autotimeAdapterZQ.setSelectedPosition(0);
                autotimeAdapterZQ.notifyDataSetChanged();
                limittime_id3 = autotime.get(0).getLimittime_id();
            }else {
                ProByCateEntity.ProBean abean = getProBeanByName(autotime, limittime_id3);
                if (abean != null) {
                    int i = autotime.indexOf(abean);
                    autotimeAdapterZQ.setSelectedPosition(i);
                    autotimeAdapterZQ.notifyDataSetChanged();
                    limittime_id3 = autotime.get(i).getLimittime_id();
                }
            }
            if(flag){
                taskCategoryAdapterCF.setSelectedPosition(0);
                taskCategoryAdapterCF.notifyDataSetChanged();
                isrepeat=Constant.list3.get(0).getLimittime_id();
            }else
            {
            ProByCateEntity.ProBean lbean= getProBeanByName(Constant.list3,isrepeat);
            if(lbean!=null){
                int i=Constant.list3.indexOf(lbean);
                taskCategoryAdapterCF.setSelectedPosition(i);
                taskCategoryAdapterCF.notifyDataSetChanged();
                isrepeat=Constant.list3.get(i).getLimittime_id();
            }
            }
            NumberFormat num = NumberFormat.getPercentInstance();
            tv_percent.setText("含服务费"+num.format(((ProByCateEntity) data).getPercent()));
            topmoney=((ProByCateEntity) data).topmoney;
            tv_zhiding_price.setText(topmoney+"");
            percent=((ProByCateEntity) data).getPercent();
            changTotalAndNeed();

        }
        if (ConstantValue.RequestKey.push_task_update.equals(actionType)) {
            ToastUtils.showShortToastSafe("发布任务成功,等待后台审核");
            PushTaskUpdateActivity.this.finish();
        }

        if ("uploadfile".equals(actionType)) {
            String url = (String) data;
            imageurl = url;
            if (ivPic != null) {
                ImageLoader.displayImage(this, ConstantValue.IMG_BASEURL_QR_CODE + url, ivPic);
            }
        }

        if (("step"+position).equals(actionType)) {
            String url = (String) data;
//            if (image != null && !url.equals(image.getTag())) {
//                image.setTag(null);
//                ImageLoader.displayImage(this, ConstantValue.IMG_BASEURL + url, image);
//                image.setTag(url);
//            }
           MyPushDetailEntity.TaskstepBean bean= taskstepBeans.get(position);
            bean.setPicture(url);
            map.put(position,bean);
            stepAdapter.setList(taskstepBeans);
        }
        if (ConstantValue.RequestKey.my_push_detail.equals(actionType)) {
            MyPushDetailEntity data1 = (MyPushDetailEntity) data;
            List<MyPushDetailEntity.TaskinfoBean> taskinfoBeans = data1.getTaskinfo();
            List<MyPushDetailEntity.TaskstepBean> taskstep = data1.getTaskstep();
            if (taskinfoBeans != null && taskinfoBeans.size() > 0) {
                MyPushDetailEntity.TaskinfoBean item = taskinfoBeans.get(0);
                tvTypeTitle.setText(item.getCatename());
                c_id = item.getC_id();
                etDanjia.setText(item.getMoney()+"");
                etShuliang.setText(item.getLastnumber()+"");
                shuliang=item.getLastnumber();
                danjia=Double.parseDouble(item.getMoney());
                //任务总价
                tvTotal.setText(String.format("%s", item.getPaymoney()));
                //是否置顶
                if(item.getTop()==0) {
                    ckZhiding.setSelected(false);
                    setZhiding(false);
                }else if(item.getTop()==1)
                {
                    ckZhiding.setSelected(true);
                    setZhiding(true);
                }

                etTaskName.setText(item.getTaskname());
                opentype= item.getOpentype()+"";
                if(opentype.equals("1")){
                    refreshType(true);
                    String url=item.getOpenurl();
                    imageurl=url;
                    if (ivPic != null) {
                        ImageLoader.displayImage(this, ConstantValue.IMG_BASEURL_QR_CODE + url, ivPic);
                    }
                }else{
                    refreshType(false);
                    etLianjie.setText(item.getOpenurl());
                }
                etInfo.setText(item.getText());

                et_tasktitle.setText(item.title);
                limittime_id1=item.limittime_id1;
                limittime_id2=item.limittime_id2;
                limittime_id3=item.limittime_id3;
                isrepeat=item.isrepeat;

                String isinfo=item.isinfo;
                if(isinfo.equals("0"))
                {
                    cb_check_other.setChecked(false);
                }else
                {
                    cb_check_other.setChecked(true);
                }


//                //任务id
//                tvTaskNumber.setText(item.getTasknum());
//                //任务总钱
//                tvTotalMoney.setText("" + item.getTotalmoney());
//                //任务名称
//                tvTaskname.setText("任务名称:" + (TextUtils.isEmpty(item.getTaskname()) ? "小白任务" : item.getTaskname()));
//                //发布时间
//                tvTasktime.setText("发布时间:" + item.getCreatetime());
//                //总量
//                tvNumber.setText("总量:" + item.getNumber());
//                //为完成量
//                tvLastnumber.setText("未完成:" + item.getLastnumber());
//
//                //任务内容
//                tvText.setText(item.getText());
                //任务图片
//                List<MyPushDetailEntity.TaskinfoBean.ImageBean> image = item.getImage();
//                if (image != null && image.size() > 0) {
//                    for (int i = 0; i < image.size(); i++) {
//                        MyPushDetailEntity.TaskinfoBean.ImageBean imageBean = image.get(i);
//                        String img = imageBean.getImg();
//                        String url = ConstantValue.IMG_BASEURL + img;
//                        addImg(url);
//                    }
//                }

                int opentype = item.getOpentype(); //1二维码  2链接
                String openurl = item.getOpenurl();
                if (opentype == 1) {
//                    tvType.setText("二维码");
//                    ivEcode.setVisibility(View.VISIBLE);
//                    tvHttp.setVisibility(View.GONE);
//                    Glide.with(this).load(ConstantValue.IMG_BASEURL + openurl).into(ivEcode);
                } else if (opentype == 2) {
//                    tvType.setText("链接");
//                    ivEcode.setVisibility(View.GONE);
//                    tvHttp.setVisibility(View.VISIBLE);
//                    tvHttp.setText(openurl);
                } else {
//                    tvTypeTitle.setVisibility(View.GONE);
//                    tvType.setVisibility(View.GONE);
//                    ivEcode.setVisibility(View.GONE);
//                    tvHttp.setVisibility(View.GONE);
                }

//                ivEcode.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        ArrayList<String> photoPaths = new ArrayList<>();
//                        photoPaths.add(ConstantValue.IMG_BASEURL + openurl);
//                        PhotoPreview.builder()
//                                .setPhotos(photoPaths)
//                                .setCurrentItem(0)
//                                .setShowDeleteButton(true)
//                                .start((Activity) context);
//                    }
//                });
            }

            if (taskstep != null && taskstep.size() > 0) {
                taskstepBeans.clear();
                taskstepBeans.addAll(taskstep);
                stepAdapter.notifyDataSetChanged();
//                mData.clear();
//                mData.addAll(taskstep);
            }
//            adapter.refresh(mData);
            getTaskType();
        }


    }

    @Override
    public void onFailed(String code, String msg) {
        dismissProgress();
        ToastUtils.showShortToastSafe(msg);
    }

    @Override
    protected void onDestroy() {
        if (image != null) {
            image.setTag(null);
        }

        if (llView != null) {
            for (int i = 0; i < llView.getChildCount(); i++) {
                View view = llView.getChildAt(i);
                ImageView ivPic = (ImageView) view.findViewById(R.id.iv_pic);
                ivPic.setTag(null);
            }
        }
        super.onDestroy();
    }


}
